<template>
  <div class="wrapper">
    <div class="header">
      <div class="logo">
        <!--<img src="../assets/images/logo.png" class="logo-img" height="18" alt="quick clip">-->
      </div>
      <div class="project-box">
        <!--<div class="user" @click="logout" title="退出">-->
        <!--<svg version="1.1" xmlns="http://www.w3.org/2000/svg" x="0px" y="0px" viewBox="0 0 40 40"-->
        <!--enable-background="new 0 0 40 40" xml:space="preserve">-->
        <!--<path fill="none" stroke="#BABABA" stroke-width="2" stroke-linecap="round"-->
        <!--stroke-linejoin="round" d="M26.4,14.1-->
        <!--C28,15.7,29,18,29,20.5c0,5-4,9-9,9s-9-4-9-9c0-2.4,1-4.6,2.5-6.2"></path>-->
        <!--<line fill="none" stroke="#BABABA" stroke-width="2" stroke-linecap="round"-->
        <!--stroke-linejoin="round" x1="20" y1="10.6" x2="20" y2="17.8"></line>-->
        <!--</svg>-->
        <!--</div>-->
      </div>
    </div>
    <div class="main">
      <div class="middle-wrap">
        <div class="left-menu">
          <vue-scroll>
            <div class="left-menu-item"
                 :class="{ active :item._id == _id}"
                 v-for="item in attachmentList"
                 @click="menuHandle(item._id)">{{item.title}}
            </div>
          </vue-scroll>
        </div>
        <div class="content">
          <div class="left">
            <div class="player-box"
                 id="volcano_player"></div>
          </div>
          <div class="right">
            <div class="preTab">
              <span @click="listTabHandle('truncation')"
                    :class="[curList === 'truncation'? 'active': '']">截短</span>
              <span @click="listTabHandle('images')"
                    :class="[curList === 'images'? 'active': '']">截图</span>
            </div>
            <div class="list-wrap">
              <vue-scroll>
                <div v-show="curList === 'truncation'">
                  <div class="vod-item"
                       v-for="(item, index) of truncationList"
                       :class="[truncationListIndex === index ? 'active': '']"
                       @click="truncationHandle(index, item._id, $event)">
                    <span class="time">{{item.time_start}} - {{item.time_end}}</span>
                    <div class="del-btn">
                      删除
                    </div>
                  </div>
                </div>
                <div v-show="curList === 'images'">
                  <div class="img-item"
                       v-for="(item, index) of imagesList"
                       @click="imagesHandle(item.filepath, item._id, $event)">
                    <img :src="item.filepath"
                         width="200"
                         height="133"
                         :alt="item.gmt">
                    <div class="del-btn">
                      删除
                    </div>
                  </div>
                </div>
              </vue-scroll>
            </div>
          </div>
        </div>
        <div class="handler-box">
          <div class="change-area">
            <div class="tab-btn"
                 :class="[curTab === 'truncation'? 'active': '']"
                 @click="tabHandle('truncation')">截短
            </div>
            <div class="tab-btn"
                 :class="[curTab === 'dot'? 'active': '']"
                 @click="tabHandle('dot')">打点
            </div>
          </div>

          <div class="dot-area"
               v-show="curTab==='truncation'">
            <div class="video-time"
                 ref="currentTimeDurationDom">
              00:00 / 00:00
            </div>
            <div class="timeline">
              <canvas id="time_line"></canvas>
            </div>

          </div>
          <v-button v-show="isShowBtn"
                    :inline="true"
                    :width="'70'"
                    :height="'38'"
                    @click="submitTruncation()"
                    style="background-color: #eea236; float: right;">放入工作台
          </v-button>
          <div class="input-area"
               v-show="curTab==='dot'">
            <div class="video-time"
                 ref="currentTimeDom">
              00:00
            </div>
            <v-input v-model="labelText"
                     :width="'530px'"
                     :size="'large'"
                     style="float: left; margin-right: 10px"></v-input>
            <v-button :inline="true"
                      :width="'70'"
                      :height="'38'"
                      style="background-color: #eea236; float: left;"
                      @click="setLabel()">保存
            </v-button>
          </div>
          <div class="btn-area">
            <v-button :inline="true"
                      :width="'46'"
                      :height="'38'"
                      v-show="curTab==='dot'"
                      @click="removeLabel()">删除
            </v-button>
            <v-button :inline="true"
                      :width="'46'"
                      :height="'38'"
                      v-show="curTab==='truncation'"
                      @click="returnVideo()">原视频
            </v-button>
            <v-button :inline="true"
                      :width="'46'"
                      :height="'38'"
                      v-show="curTab==='truncation'"
                      @click="screenshot()">截图
            </v-button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import vuescroll from 'vuescroll'
import VInput from '../components/common/v-input'
import VButton from '../components/common/v-button'

export default {
  name: 'home',
  components: {
    VButton, VInput
  },
  data () {
    return {
      _id: '',
      card_id: '',
      dotList: [],
      truncationList: [],
      attachmentList: [],
      attachmentActive: '',
      truncationListIndex: null,
      imagesList: [],
      player: null,
      playerStatus: 'waiting',
      timeCaliper: null,
      curTab: 'truncation',
      curList: 'truncation',
      selectStartTime: 0,
      selectEndTime: 0,
      activeLabelTime: 0,
      currentTime: 0,
      labelText: '',
      currentTimeDurationDom: null,
      currentTimeDom: null,
      isLabelAdd: true,
      isInitVideo: true,
      isShowBtn: true
    }
  },
  methods: {
    tabHandle (cur) {
      this.curTab = cur
      if (cur === 'dot') {
        this.timeCaliper.clearSelectArea()
        this.selectStartTime = 0
        this.selectEndTime = 0
        this.isShowBtn = false
      } else {
        this.isShowBtn = true
      }
    },
    listTabHandle (cur) {
      this.curList = cur
    },
    /**
     * 提交截取
     */
    submitTruncation () {
      let that = this
      console.log(this.selectStartTime, this.selectEndTime)
      let params = {
        _id: that._id,
        time_start: that.selectStartTime,
        time_end: that.selectEndTime
      }
      that.$axios.post('/workbenchadmin/vod/clipVideo', params).then(function (res) {
        that.truncationList.unshift({
          filepath: res.data.filepath,
          time_start: that.secondToTime(that.selectStartTime),
          time_end: that.secondToTime(that.selectEndTime),
          _id: res.data._id
        })
        that.timeCaliper.clearSelectArea()
        that.selectStartTime = 0
        that.selectEndTime = 0
        that.truncationListIndex = null
        that.$toasted.success('截取成功')
      }).catch(function (err) {
        console.log(err)
        that.$toasted.error('截取失败')
      })
    },

    returnVideo () {
      this.isInitVideo = true
      this.truncationListIndex = null
      this.player.loadVideo({
        url: this.videoUrl
      })
    },

    /**
     * 截短播放控制
     */
    truncationHandle (index, id, event) {
      let that = this
      if (event.target.className === 'del-btn') {
        let r = confirm('确认删除吗？')
        if (r) {
          that.delClipVideoDelete(id)
        }
      } else {
        that.isInitVideo = false
        that.truncationListIndex = index
        that.player.label.remove(that.dotList)

        let url = this.truncationList[index].filepath
        this.player.loadVideo({
          url: url,
          title: this.truncationList[index].time_start + ' - ' + this.truncationList[index].time_end
        })
      }
    },

    delClipVideoDelete (id) {
      let that = this
      that.$axios.post('/workbenchadmin/vod/clipVideoDelete', {
        _id: id,
        card_id: that.card_id
      }).then(function (res) {
        if (res.status == 0) {
          for (let i = 0; i < that.truncationList.length; i++) {
            if (that.truncationList[i]._id == id) {
              that.truncationList.splice(i, 1)
            }
          }
          that.player.loadVideo({
            url: '',
            title: ''
          })
          that.player.label.remove(that.dotList)
          that.$toasted.success('删除成功')
        } else {
          that.$toasted.error('error')
        }
      }).catch(function (err) {
        console.log(err)
        that.$toasted.error('ERROR')
      })
    },

    delClipImageDelete (id) {
      let that = this
      that.$axios.post('/workbenchadmin/vod/clipImageDelete', {
        _id: id,
        card_id: that.card_id
      }).then(function (res) {
        if (res.status == 0) {
          for (let i = 0; i < that.imagesList.length; i++) {
            if (that.imagesList[i]._id == id) {
              that.imagesList.splice(i, 1)
            }
          }
          that.$toasted.success('删除成功')
        } else {
          that.$toasted.error('error')
        }
      }).catch(function (err) {
        console.log(err)
        that.$toasted.error('ERROR')
      })
    },

    imagesHandle (url, id, event) {
      if (event.target.className === 'del-btn') {
        let r = confirm('确认删除吗？')
        if (r) {
          this.delClipImageDelete(id)
        }
      } else {
        window.open(url)
      }
    },

    /**
     * 设置打点
     */
    setLabel () {
      let that = this
      if (this.labelText === '') {
        return this.$toasted.show('请输入打点内容')
      }
      let obj = {}
      if (this.isLabelAdd) {
        obj.time = this.currentTime
        obj.text = this.labelText
        that.$axios.post('/workbenchadmin/vod/dot', {
          _id: that._id,
          gmt: obj.time,
          content: obj.text
        }).then(function (res) {
          if (res.status == 0) {
            that.player.label.set(obj)
            that.labelText = ''
            that.activeLabelTime = ''
            that.isLabelAdd = true
          } else {
            that.$toasted.error('error')
          }
        }).catch(function (err) {
          console.log(err)
          that.$toasted.error('ERROR')
        })
      } else {
        obj.time = this.activeLabelTime
        obj.text = this.labelText
        that.$axios.post('/workbenchadmin/vod/dotEdit', {
          _id: that._id,
          gmt: obj.time,
          content: obj.text
        }).then(function (res) {
          if (res.status == 0) {
            that.player.label.set(obj)
            that.labelText = ''
            that.activeLabelTime = ''
            that.isLabelAdd = true
          } else {
            that.$toasted.error('error')
          }
        }).catch(function (err) {
          console.log(err)
          that.$toasted.error('ERROR')
        })
      }

      console.log(this.selectStartTime, this.selectEndTime)
    },
    /**
     * 移除打点
     */
    removeLabel () {
      let that = this
      that.$axios.post('/workbenchadmin/vod/dotDelete', {
        _id: that._id,
        gmt: that.activeLabelTime
      }).then(function (res) {
        if (res.status == 0) {
          that.player.label.remove(that.activeLabelTime)
          that.labelText = ''
          that.activeLabelTime = ''
          that.isLabelAdd = true
        } else {
          that.$toasted.error('error')
        }
      }).catch(function (err) {
        that.$toasted.error('ERROR')
      })
    },
    /**
     * 截图
     */
    screenshot () {
      let that = this
      let params = {
        _id: that._id,
        gmt: that.currentTime
      }
      that.$axios.post('/workbenchadmin/vod/clipImage', params).then(function (res) {
        console.log(res)
        that.imagesList.unshift({
          filepath: res.data.filepath,
          gmt: that.currentTime,
          _id: res.data._id
        })
        that.$toasted.success('图片截取成功')
      }).catch(function (err) {
        that.$toasted.error('图片截取失败')
      })
    },
    /**
     * 获取地址
     */
    getVideoUrl () {
      let that = this
      let params = {
        _id: that._id,
        card_id: that.card_id
      }
      that.$axios.post('/workbenchadmin/vod', params).then(function (res) {
        console.log(res)
        let tempDots = []
        for (let item of res.data.dots) {
          let obj = {
            time: item.gmt,
            text: item.content
          }
          tempDots.push(obj)
        }
        that.dotList = tempDots
        that.truncationList = res.data.clip_videos || []
        that.imagesList = res.data.clip_images || []
        that.attachmentList = res.data.attachment_list || []
        that.videoUrl = res.data.filepath
        that.player.loadVideo({
          url: res.data.filepath,
          title: 'VIDEO PLAYER CC'
        })
      }).catch(function (err) {
        console.log(err)
        that.$toasted.error('获取失败')
      })
    },

    menuHandle (id) {
      this._id = id
      let url = window.location.origin + '?_id=' + this._id + '&card_id=' + this.card_id
      history.pushState({}, '', url)
      this.getVideoUrl()
    },

    drawImg () {
      this.player.drawImg('')
    },
    logout () {
      window.location.href = '/admin/sign/out'
    },
    secondToTime (second) {
      const add0 = (num) => num < 10 ? '0' + num : '' + num
      const hour = Math.floor(second / 3600)
      const min = Math.floor((second - hour * 3600) / 60)
      const sec = Math.floor(second - hour * 3600 - min * 60)
      return (hour > 0 ? [hour, min, sec] : [min, sec]).map(add0).join(':')
    },
    getQueryString (name) {
      let reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)')
      let r = window.location.search.substr(1).match(reg)
      if (r != null) return unescape(r[2])
      return null
    }
  },
  mounted () {
    let that = this
    this.$nextTick(() => {
      // query _id
      that._id = that.getQueryString('_id')
      that.card_id = that.getQueryString('card_id')

      let options = {
        container: document.querySelector('#volcano_player'),
        autoplay: false
      }

      let timeCaliperOption = {
        canvas: '#time_line',
        width: 476,
        getSelectArea: (obj) => {
          // console.log(obj)
          that.selectStartTime = obj.startTime
          that.selectEndTime = obj.endTime
        },
        getSelectTime: (time) => {
          // console.log(time)
          that.selectStartTime = 0
          that.selectEndTime = 0
        },
        seek: (time) => {
          console.log(time)
          that.player.seek(time)
        }
      }

      that.player = new window.VolcanoPlayer(options)
      that.timeCaliper = new TimeCaliper(timeCaliperOption)

      that.currentTimeDom = that.$refs.currentTimeDom
      that.currentTimeDurationDom = that.$refs.currentTimeDurationDom

      that.player.on('loadedmetadata', () => {
        //                    console.log(that.secondToTime(that.player.video.duration))
        that.timeCaliper.clearTimeStick()
        that.timeCaliper.draw(that.player.video.duration)
        that.currentTimeDurationDom.innerText = that.secondToTime(that.player.video.currentTime) + ' / ' + that.secondToTime(that.player.video.duration)

        that.player.label.on('click', (info) => {
          that.isLabelAdd = false
          that.activeLabelTime = info.time
          that.labelText = info.text
        })
        // init打点数据
        if (that.isInitVideo) {
          that.player.label.set(that.dotList)
        }
      })

      that.player.on('playing', () => {
        that.playerStatus = 'playing'
      })

      that.player.on('waiting', () => {
        that.playerStatus = 'waiting'
      })

      that.player.on('pause', () => {
        that.playerStatus = 'pause'
      })

      that.player.on('timeupdate', () => {
        if (that.selectEndTime) {
          if (that.player.video.currentTime > that.selectEndTime) {
            that.player.video.currentTime = that.selectStartTime
          }
        }
        if (that.playerStatus === 'playing') {
          that.timeCaliper.timeupdate(that.player.video.currentTime)
        }

        that.currentTime = that.player.video.currentTime
        that.currentTimeDom.innerText = that.secondToTime(that.player.video.currentTime)
        if (isNaN(that.player.video.duration)) return
        that.currentTimeDurationDom.innerText = that.secondToTime(that.player.video.currentTime) + ' / ' + that.secondToTime(that.selectEndTime === 0 ? that.player.video.duration : that.selectEndTime)
      })

      that.player.on('canplay', () => {
        if (that.curTab === 'dot') return
        that.player.play()
      })

      that.player.on('playerready', () => {
        // 获取地址
        that.getVideoUrl()
      })

      that.player.video.addEventListener('seeked', () => {
        if (that.curTab === 'dot') {
          that.player.pause()
        }
      })
    })
  }
}
</script>

<style lang="scss">
@import "../assets/common/styles/variables.scss";
@import "../assets/common/styles/mixin.scss";

/*global*/
.module {
  .module-title {
    height: 30px;
    line-height: 30px;
    color: $color-font-master;
    font-size: $fontsize-small;

    .active {
      color: $color-font-active;
    }

    span {
      display: inline-block;
      padding: 0 18px;
      height: 30px;
      background-color: $color-background-master;
    }
  }
}

.tabs {
  width: 100%;
  font-size: $fontsize-small;
  color: $color-font-master;
  @include clearfix();

  .tab {
    position: relative;
    float: left;
    display: inline-block;
    cursor: pointer;

    span {
      display: inline-block;
      height: 30px;
      line-height: 30px;
      padding: 0 18px;
      cursor: pointer;
      background-color: transparent;

      &:hover {
        color: $color-font-active;
      }
    }

    &.active {
      color: $color-font-active;
      background-color: $color-background-master;

      &::after {
        position: absolute;
        bottom: 0;
        left: 15%;
        display: inline-block;
        content: "";
        width: 70%;
        height: 2px;
        border-radius: 2px;
        background: $color-background-light-s;
      }
    }
  }
}

.date-picker-input {
  display: inline-block;
  width: 158px;
  height: 28px;
  line-height: 28px;
  align-items: center;
  text-align: center;
  font-size: $fontsize-small;
  color: $input-color;
  border: 1px solid #333;
  background-color: $input-bgc;
  outline: none;
}

.mx-input-append {
  background-color: transparent;
}

.mx-calendar-icon {
  color: $color-font-master;
}

/*layout*/
.wrapper {
  position: relative;
  width: 100%;
  min-width: 1280px;
  height: 100%;
  background-color: $color-background-dark;
  overflow: hidden;
}

.header {
  height: 40px;
  background: $color-background-master;
  border: 2px solid $color-background-dark;
  border-top: 0;
  box-sizing: border-box;

  .logo {
    height: 40px;
    float: left;
  }

  .logo-img {
    margin-top: 10px;
    margin-left: 6px;
  }

  .project-box {
    text-align: right;
    width: 660px;
    height: 40px;
    float: right;
    padding-right: 20px;
  }

  .layout {
    position: relative;
    display: inline-block;
    width: 116px;
    line-height: 38px;
    vertical-align: top;
    text-align: left;
    border-right: 1px solid $color-border-master;

    .layout-icon {
      position: absolute;
      top: 12px;
      left: 0;
      width: 16px;
      height: 16px;
    }

    .layout-text {
      font-size: 12px;
      color: $color-font-master;
      padding: 0 10px 0 25px;
    }

    .layout-arrow {
      width: 10px;
    }
  }

  .network-status {
    display: inline-block;
    width: 40px;
    height: 40px;
    overflow: hidden;
    text-align: center;
    vertical-align: top;
  }

  .message {
    display: inline-block;
    width: 40px;
    height: 40px;
    overflow: hidden;
    text-align: center;
    vertical-align: top;
  }

  .user {
    display: inline-block;
    line-height: 38px;
    cursor: pointer;
    margin-left: 12px;

    svg {
      width: 32px;
      height: 40px;
      vertical-align: top;
    }

    span {
      font-size: 12px;
      color: $color-font-master;
    }
  }
}

.left-wrap,
.middle-wrap,
.right-wrap,
.bottom-wrap {
  border: 2px solid $color-background-dark;
  background-color: $color-background-master;
}

.middle-wrap {
  position: relative;

  .content {
    background-color: #000;
    border-bottom: 2px solid #000;
    @include clearfix;
  }

  .left {
    width: 810px;
    float: left;
  }

  .right {
    width: 214px;
    float: left;
  }
}

.main {
  position: relative;
  height: calc(100% - 40px);
}

.middle-wrap {
  width: 1152px;
  height: 100%;
  margin: 0 auto;
}

.left-menu {
  float: left;
  width: 128px;
  height: 458px;
}

.left-menu-item {
  width: 100%;
  height: 40px;
  line-height: 40px;
  box-sizing: border-box;
  padding: 0 6px;
  font-size: 14px;
  color: #fff;
  background-color: #333333;
  margin-bottom: 4px;
  cursor: pointer;

  &.active {
    background: rgb(238, 162, 54);
  }
}

.player-box {
  width: 100%;
  height: 456px;
  overflow: hidden;
  background-color: #000;
}

.handler-box {
  padding: 10px 20px;
  box-sizing: border-box;
  @include clearfix;

  .change-area {
    width: 100px;
    float: left;
    text-align: center;
    background-color: #0f0f0f;

    .tab-btn {
      width: 50px;
      float: left;
      font-size: 12px;
      height: 38px;
      line-height: 38px;
      color: $color-font-master;
      cursor: pointer;

      &.active {
        background-color: rgb(238, 162, 54);
        color: $color-font-active;
      }
    }
  }
}

.input-area {
  width: 700px;
  float: left;
  margin-right: 20px;

  .video-time {
    width: 80px;
    height: 40px;
    line-height: 40px;
    color: #fff;
    text-align: center;
    float: left;
    font-size: 12px;
  }
}

.dot-area {
  width: auto;
  float: left;
  /*margin-right: 20px;*/

  .video-time {
    width: 130px;
    height: 40px;
    line-height: 40px;
    color: #fff;
    text-align: center;
    float: left;
    font-size: 12px;
  }

  .timeline {
    width: 476px;
    height: 38px;
    float: left;
    margin-right: 16px;
    background-color: #0f0f0f;
    opacity: 0.7;
  }
}

.btn-area {
  width: 110px;
  float: left;

  button {
    margin-right: 6px !important;
  }
}

.list-wrap {
  height: 424px;
  width: 200px;

  .vod-item {
    position: relative;
    width: 188px;
    height: 86px;
    margin: 0 auto 5px;
    border: none;
    cursor: pointer;
    background: #272727
      url("")
      no-repeat left bottom;
    background-size: 200px 86px;

    &.active {
      background-color: #fa9e48;
    }

    .time {
      float: left;
      color: $color-font-light;
      font-size: $fontsize-small;
      padding: 10px;
    }
  }

  .img-item {
    width: 180px;
    position: relative;
    height: 110px;
    margin: 0 auto 5px;
    background-color: #272727;
    border: none;
    cursor: pointer;

    img {
      width: 100%;
      height: 100%;
      border: none;
    }
  }

  .del-btn {
    position: absolute;
    right: 6px;
    bottom: 6px;
    color: #fff;
    font-size: 12px;
    width: 38px;
    height: 26px;
    text-align: center;
    line-height: 26px;
  }
}

.preTab {
  height: 32px;
  line-height: 26px;
  color: $color-font-master;
  font-size: 12px;

  span {
    display: inline-block;
    margin: 0 10px;
    padding: 0 4px;
    border-bottom: 2px solid transparent;
    box-sizing: border-box;
    cursor: pointer;

    &:hover {
      color: $color-font-active;
    }

    &.active {
      color: $color-font-active;
      border-bottom: 2px solid $color-font-active;
    }
  }
}
</style>
